package sncf.main;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

import sncf.client.ActionTask;
import sncf.client.ConfirmTask;
import sncf.client.SaveTask;
import sncf.client.SncfAlertView;
import sncf.utils.AdminUtils;
import sncf.utils.ConfigLoader;
import sncf.utils.Converter;
import sncf.utils.Referential;

public class Starter {

	private static final String ROUEN_ARRIVEE_URL = "http://www.gares-en-mouvement.com/fr/frurd/horaires-temps-reel/arr/";
	private static final String PARIS_ST_LAZARE_ARRIVEE_URL = "http://www.gares-en-mouvement.com/fr/frpsl/horaires-temps-reel/arr/";

	// private static final String timeToArchive = "02h00mn";

	public static void main(String[] args) {
		try {
			Referential ref = Referential.getInstance();
			final int refreshMinutes = (Integer) ConfigLoader.getInstance()
					.get(ConfigLoader.REFRESH_MINUTES_PROPERTY);

			SncfAlertView view = new SncfAlertView();
			final Timer timer = new Timer();

			final Date now = new Date();
			ActionTask alertTask = new ActionTask(view);

			SaveTask saveTask = new SaveTask();
			Date saveDate = getDateSave();

			timer.schedule(alertTask, now, refreshMinutes * 60 * 1000);
			timer.schedule(saveTask, saveDate, 24 * 60 * 60 * 1000);

			Boolean lateConfirmationServiceActivated = (Boolean) ConfigLoader
					.getInstance().get(
							ConfigLoader.LATE_CONFIRMATION_SERVICE_PROPERTY);
			boolean confirmationActivated = lateConfirmationServiceActivated != null ? lateConfirmationServiceActivated
					: false;
			Date timeToConfirm = null;

			if (confirmationActivated) {
				Calendar cal = Calendar.getInstance();
				cal.setTime(new Date());
				cal.add(Calendar.DAY_OF_MONTH, 1);
				cal.set(Calendar.HOUR_OF_DAY, 14);
				cal.set(Calendar.MINUTE, 30);
				cal.set(Calendar.SECOND, 0);
				timeToConfirm = cal.getTime();
				ConfirmTask confirmTask = new ConfirmTask();

				timer.schedule(confirmTask, timeToConfirm, 24 * 60 * 60 * 1000);
				ref.setNextConfirmDate(timeToConfirm);
			}

			ref.setNextSaveDate(saveDate);
			System.out.println("Save task created for date " + saveDate);

			if (confirmationActivated) {
				System.out.println("Confirm task created for date "
						+ timeToConfirm);
			}

			// TEST CODE
			// List<Train> trainList = new ArrayList<Train>();
			// Train train = new Train("Intercite", "3131", new Date(),
			// "Rouen Rive Droite", "Paris Saint Lazare", "Retard: 45min",
			// "18");
			// trainList.add(train);
			// ref.addAlertTrainList(trainList);
			// TEST CODE

		} catch (Exception e) {
			e.printStackTrace();
			Referential.getInstance().saveAndPurgeAlertTrainList();
			AdminUtils.notifySystemAdmin(e);
		}

	}

	private static Date getDateSave() {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());

		String timeToArchive = (String) ConfigLoader.getInstance().get(
				ConfigLoader.SAVE_TIME_PROPERTY);
		int timeToArchiveMinutes = Converter
				.convertStringDayToMinutes(timeToArchive);
		int minutesToday = Converter.convertTimeToDayMinutes(cal.getTime());

		if (minutesToday >= timeToArchiveMinutes) {
			cal.add(Calendar.DAY_OF_MONTH, 1);
		}
		int[] splitTime = splitTime(timeToArchive);

		cal.set(Calendar.HOUR_OF_DAY, splitTime[0]);
		cal.set(Calendar.MINUTE, splitTime[1]);
		cal.set(Calendar.SECOND, 0);

		return cal.getTime();
	}

	private static int[] splitTime(String time) {
		int[] split = null;

		if (time != null && time.contains("h") && time.contains("min")) {
			String[] tokens = time.split("h");
			if (tokens != null && tokens.length == 2) {
				split = new int[] { Integer.parseInt(tokens[0]),
						Integer.parseInt(tokens[1].replaceAll("min", "")) };
			}
		}

		return split;
	}

	private static void testCode() {
		// final String GRAND_VOYAGEUR_LOGIN_PAGE_URL =
		// "https://www.programme-voyageur.sncf.com";
		// final String login = "881919632";
		// final String password = "thy270187";
		// WebClient webClient = null;
		//
		// try {
		//
		// final boolean jsEnabled = true;
		// final boolean appletEnabled = false;
		// webClient = WebTools.getWebClient(jsEnabled, appletEnabled);
		// HtmlPage webHomePage;
		// webHomePage = webClient.getPage(GRAND_VOYAGEUR_LOGIN_PAGE_URL);
		//
		// final HtmlForm form = webHomePage
		// .getFormByName("authentification-form");
		//
		// final HtmlSubmitInput submitButton = form
		// .getInputByValue("Se connecter");
		// final HtmlTextInput loginTextField = form
		// .getInputByName("esb.numeroCarteAuthent");
		// final HtmlPasswordInput passwordTextField = (HtmlPasswordInput) form
		// .getInputByName("esb.motDePasse");
		//
		// loginTextField.setValueAttribute(login);
		// passwordTextField.setValueAttribute(password);
		//
		// // Now submit the form by clicking the button and get back the
		// // second
		// // page.
		// final HtmlPage resultWebPage = submitButton.click();
		//
		// int i = 10;
		// while (resultWebPage == null
		// || resultWebPage
		// .getElementById("iframe-formulaire-contact")
		// .getChildNodes().isEmpty() && i > 0) {
		// Thread.sleep(1000);
		// i--;
		// }
		//
		// if (resultWebPage != null
		// && !resultWebPage
		// .getElementById("iframe-formulaire-contact")
		// .getChildNodes().isEmpty()) {
		// HtmlForm coordForm = resultWebPage
		// .getFormByName("page_vosCoordonnees");
		//
		// if (coordForm != null) {
		//
		// }
		// }
		//
		// URL url = new URL(
		// "https://formulaire.sncf.com/fag-front/forms/funweb/blocks/page_vosCoordonnees");
		// WebRequest postRequest = new WebRequest(url);
		// postRequest.setHttpMethod(HttpMethod.POST);
		//
		// Map<String, String> headers = new HashMap<String, String>();
		// headers.put("TS", "VL");
		// headers.put("CIV", "M.");
		// headers.put("SMILES", "29090109881919632");
		// headers.put("NOM", "MORAIS DA CRUZ");
		// headers.put("PRENOM", "THIERRY");
		// headers.put("EMAIL", "thierry.moraisdacruz@gmail.com");
		// headers.put("ADRESSE1", "APPARTEMENT A502");
		// headers.put("ADRESSE2", "");
		// headers.put("ADRESSE3", "22 BOULEVARD DE L EUROPE");
		// headers.put("ADRESSE4", "");
		// headers.put("CPOSTAL", "76100");
		// headers.put("VILLE", "ROUEN");
		// headers.put("PAYS", "");
		// headers.put("NUMCLI", "11858465");
		// headers.put("CONTACT", "");
		// headers.put(
		// "URL",
		// "https://www.programme-voyageur.sncf.com/logue/information/maj-client?retour=FormulaireContact");
		// headers.put("PROVENANCE", "WEB");
		// headers.put("initWithContextLoading", "true");
		//
		// postRequest.setAdditionalHeaders(headers);
		//
		// String requestBody =
		// "TS=VL&CIV=M.&SMILES=29090109881919632&NOM=MORAIS+DA+CRUZ&"
		// + "PRENOM=THIERRY&EMAIL=thierry.moraisdacruz%40gmail.com&"
		// +
		// "ADRESSE1=APPARTEMENT+A502&ADRESSE2=&ADRESSE3=22+BOULEVARD+DE+L+EUROPE&"
		// + "ADRESSE4=&CPOSTAL=76100&VILLE=ROUEN&PAYS=&NUMCLI=11858465&"
		// +
		// "CONTACT=&URL=https%3A%2F%2Fwww.programme-voyageur.sncf.com%2Flogue%2Finformation%2Fmaj-client%3Fretour%3DFormulaireContact&"
		// + "PROVENANCE=WEB&" + "initWithContextLoading=true";
		//
		// postRequest.setRequestBody(requestBody);
		//
		// WebResponse webResponse = webClient.loadWebResponse(postRequest);
		// String response = webResponse.getContentAsString();
		//
		// System.out.println(response);

		// String grandVoyageurMainPageContent = resultWebPage.asXml();
		// System.out.println(grandVoyageurMainPageContent);
	}
}
